import * as qiniu from 'qiniu-js'
import { commonAction } from '@/utils/common'
// qiniu配置参考 https://developer.qiniu.com/kodo/sdk/1283/javascript
// obj 是 el-upload 接收到的 object
export const upload = (token: string, key: string, obj: any, next: any, error: any, complete: any) => {
  const { file } = obj
  const putExtra = {}
  // fname: string，文件原文件名
  // params: object，用来放置自定义变量
  // mimeType: null || array，用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
  const config = {}
  // @ts-ignore: Unreachable code error
  const observable = qiniu.upload(file, key, token, putExtra, config)
  /**
   * @param file 上传文件
   * @param key 目标文件名
   * @param token 上传凭证
   * @param putExtra 上传文件的相关资源信息配置
   * @param config 上传任务的配置
   */
  const subscription = observable.subscribe(next, error, complete)
  return subscription
}
export const uploadQiniu = (tokenData: any, request: any) => {
  const data = { url: '/base/action/qiniu/token', method: 'GET', data: tokenData }
  return commonAction(data).then((res: any) => {
    if (res && res.success && res.data) {
      const token = res.data.uptoken
      const key = res.data.scope ? res.data.scope.split(':')[1] : ''
      const domain = res.data.domain
      return upload(
        token,
        key,
        request,
        next => { // 上传进度
          request.onProgress({ percent: next.total.percent }, request.file) // 走el-upload的on-progress回调
        },
        error => { // 上传失败
          request.onError(error) // 走el-upload的on-error回调
        },
        complete => { // 上传完成
          const keyes = complete.key
          complete.key = keyes
          complete.domain = domain
          request.onSuccess(complete, request.file) // 走el-upload的on-success回调
        }
      )
    } else {
      return false
    }
  })
}
